<?php
class MemberController extends Controller
{
	/**
    * Set layout
   */
   public $layout = '//layouts/cms/main';
   
   /**
	 * action array filter
	 */
   public function filters()
	{
		return array(
         'accessControl', // perform access control for CRUD operations
      );
	}
   
   /**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
   public function accessRules(){
      $rights = Role::getRights($this->id);
      return $rights;
   }
   
   /**
	 * Check login all action
	 */
   public function beforeAction($action){
      if(is_null(Yii::app()->user->id))
         $this->redirect('/admin/default/login');
      else
         return true;
   }
   
   public function actionIndex()
	{
	   $page = Yii::app()->request->getParam('page',1); // Lấy số trang
      $limit = Yii::app()->request->getParam('limit',10); // Lấy số dòng hiển thị trên grid
      $sidx = isset($_GET['sidx']) ?  $_GET['sidx'] : 'CreateDate'; // Lấy trường cần sắp xếp
      $sord = isset($_GET['sord']) ? $_GET['sord'] : 'DESC'; // Lấy giá trị muốn sắp xếp
      $start = $limit*$page - $limit; // Thứ tự bản ghi bắt đầu lấy
      $rowList = array(10,20,30,50,100);  
      //Biến xác định phiên làm việc của user
      $session_user = md5(time());
      Yii::app()->session['session_user'] = $session_user;
      
	   $model = new Member();
      $sql = "SELECT 
                  member.*,
                  MembergroupName 
               FROM 
                  member 
               INNER JOIN membergroup ON member.MemberGroupID = membergroup.MemberGroupID
               WHERE IsAdmin = 1
               ORDER BY 
                  $sidx $sord 
               LIMIT $start , $limit";
      $db = Yii::app()->db;
      $cmd = $db->createCommand($sql);
      $list = $cmd->queryAll();
      $total_record = $model->countByAttributes(array('IsAdmin' => 1));
      if(!is_numeric($page)) $page = 1;
      if(!is_numeric($limit)) $limit = 10;
      if( $total_record >0 ) {
      	$total_pages = ceil($total_record/$limit);
      } else {
      	$total_pages = 0;
      }
      
		$this->render('index',array("model" => $model,
                                  "session_user" => $session_user,
                                  "list" => $list,
                                  "rowList" => $rowList,
                                  "page" => $page,
                                  "start" => $start,
                                  "limit" => $limit,
                                  "sidx" => $sidx,
                                  "sord" => $sord,
                                  "total_record" => $total_record,
                                  "total_pages" => $total_pages,));
	}
   
   /**
    * Action create member
   */
   public function actionCreate(){
      if(is_null($user_id = Yii::app()->user->id))
         $this->redirect('/site/login');
      else{
         $model = new Member();
         $session_user = Yii::app()->session['session_user'];
         $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
         $message = '';
         if(isset($_POST['Member'])){
            
            $model->attributes = $_POST['Member'];
            $model->CreateDate = time();
            $model->IsAdmin = 1;
            //CVarDumper::dump($model->attributes,10,true);die();
            $model->Password = md5($model->Password);
            $model->repeatPassword = md5($model->repeatPassword);
            $model->Birthday = date("Y-m-d", strtotime(str_replace('/', '-', $model->Birthday)));
            if($model->validate()){
               $message = "Tạo tài khoản thành công";
               $model->save();
               if($action_user == 'save'){
                  $this->redirect('/index.php/admin/'.$this->id);
               }
            }
         }
         $list_group = array(); // Danh sách các nhóm
         $membergroup = new Membergroup();
         $object = $membergroup->findAll("IsActive =:IsActive",array(":IsActive" => 1));
         if(count($object) > 0){
            foreach($object as $item){
               $list_group[$item->attributes['MemberGroupID']] = $item->attributes['MembergroupName'];
            }
         }
         $this->pageTitle = 'Tạo tài khoản';
         $this->layout = '//layouts/cms/create';
         $this->render('create',array('model'=>$model,
                                       'session_user' => $session_user,
                                       'list_group' => $list_group,'message' => $message));
      }
      
   }
   
   /**
    * Action edit member
   */
   public function actionEdit(){
      $session_user = Yii::app()->session['session_user'];
      $action_user = Yii::app()->request->getParam('action_user',''); // Biến xác định user ấn apply hay save
      $message = '';
      $id = Yii::app()->request->getParam('id',0);
      $model  = new Member("update");
      $model->attributes = $model->findByPk($id)->attributes;
      $model->MemberID = $id;
      if(isset($_POST['Member'])){
         $model = Member::model()->findByPk($id);
         $model->MemberGroupID = $_POST['Member']['MemberGroupID'];
         if($model->MemberGroupID == 1 || $model->MemberGroupID == 2){
            $message = "Cập nhật thành công";
            $model->save(false);
            if($action_user == 'save'){
               $this->redirect('/index.php/admin/'.$this->id);
            }
         }
      }
      $list_group = array(); // Danh sách các nhóm
      $membergroup = new Membergroup();
      $object = $membergroup->findAll("IsActive =:IsActive",array(":IsActive" => 1));
      if(count($object) > 0){
         foreach($object as $item){
            $list_group[$item->attributes['MemberGroupID']] = $item->attributes['MembergroupName'];
         }
      }
      $this->layout = '//layouts/cms/create';
      $this->render('edit',array('model' => $model,
                                 'session_user' => $session_user,
                                 'list_group' => $list_group,
                                 'message' => $message
                                 ));
   }
   
   /**
    * Deactive record
   */
	public function actionDeactive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == $_SESSION['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE member SET IsActive = 0 WHERE MemberID IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   
   /**
    * Active record
   */
	public function actionActive(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == $_SESSION['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'UPDATE member SET IsActive = 1 WHERE MemberID IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
   /**
    * Delete record
   */
	public function actionDelete(){
      $error = 1;
      $record_affected = 0;
      $list_id = Yii::app()->request->getParam('list_id',array());
      $session_user = Yii::app()->request->getParam('session_user','');
      if($session_user == $_SESSION['session_user'])
      {
         if(count($list_id) > 0){
            $sql = 'DELETE FROM member WHERE MemberID IN(-1';
            foreach ($list_id as $item){
               if(is_numeric($item))
                  $sql .= ',' . $item;
            }
            $sql .= ')';
            $db = Yii::app()->db;
            $cmd = $db->createCommand($sql);
            $record_affected = $cmd->execute();
            if($record_affected >= 0){
               $error = 0;
            }else{
               $error = 1;
            }
         }
         
      }
      echo json_encode(array('error' => $error,
                             'record_affected' => $record_affected)); 
	}
   
	// Uncomment the following methods and override them if needed
	/*
	public function filters()
	{
		// return the filter configuration for this controller, e.g.:
		return array(
			'inlineFilterName',
			array(
				'class'=>'path.to.FilterClass',
				'propertyName'=>'propertyValue',
			),
		);
	}

	public function actions()
	{
		// return external action classes, e.g.:
		return array(
			'action1'=>'path.to.ActionClass',
			'action2'=>array(
				'class'=>'path.to.AnotherActionClass',
				'propertyName'=>'propertyValue',
			),
		);
	}
	*/
}
?>